import cv2
import glob
import subprocess,os
def resize(img_array, align_mode):
        _height = len(img_array[0])
        _width = len(img_array[0][0])
        for i in range(1, len(img_array)):
            img = img_array[i]
            height = len(img)
            width = len(img[0])
            if align_mode == 'smallest':
                if height < _height:
                    _height = height
                if width < _width:
                    _width = width
            else:
                if height > _height:
                    _height = height
                if width > _width:
                     _width = width

        for i in range(0, len(img_array)):
            img1 = cv2.resize(img_array[i], (_width, _height), interpolation=cv2.INTER_CUBIC)
            img_array[i] = img1

        return img_array, (_width, _height)

# 从视频中提取音频
def VideoToAudio(videoname):
    audioname = videoname.split('.')[0] + '.mp3'
    subprocess.call('ffmpeg -i ' + videoname+ ' -f mp3 ' + audioname, shell=True)
    return audioname

# 图片合成视频
def pic_to_video(pic_list, video_name, fps):
    """
    图片合成视频
    :param pic_list: 图片路径列表
    :param video_name: 生成视频的名字
    :param fps: 1s显示多少张图片
    :param pic_size: 图片尺寸
    :return:
    """

    img_array = []

    for filename in glob.glob(pic_list+'/*.jpg'):
        img = cv2.imread(filename)
        if img is None:
            print(filename + " is error!")
            continue
        img_array.append(img)


    # 图片的大小需要一致
    img_array, size = resize(img_array, 'largest')
    # 'mp4v' 生成mp4格式的视频
    # 'DIVX' 生成avi格式的视频
    if ".mp4" in video_name:
        video = cv2.VideoWriter(video_name, cv2.VideoWriter_fourcc(*'mp4v'), fps, size)
    elif ".avi" in video_name:
        video = cv2.VideoWriter(video_name, cv2.VideoWriter_fourcc(*'DIVX'), fps, size)
    else:
        print("格式错误")
        return

    for i in range(len(img_array)):
        video.write(img_array[i])
    video.release()
    videoname =video_name
    return videoname



# 音视频合成
def video_add_audio(originvideo,pic_list, video_name, fps, final_video):
    audio = VideoToAudio(originvideo)
    video_minus_audio =pic_to_video(pic_list,video_name,fps)
    subprocess.call('ffmpeg -i ' + video_minus_audio

    + ' -i ' + audio + ' -strict -2 -f mp4 '

    + final_video, shell=True)
    os.remove(audio)
    os.remove(video_minus_audio)



